﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using PPIDesktopClient.General;
using PPIMobileInterface.Entities;
using System.Collections;
using PPIDesktopClient.Entities;
using PPIDesktopClient.Logic;
using PPIDesktopClient.General;
using VMind.Global;

namespace PPIDesktopClient
{
    public partial class frmSettingMobile : frmDialogBase
    {
        ESettingsStructure m_MobileSettings;
        DownloadFile m_DownloadFile;
        FileInfo _MobileDatabase;
        private string[] m_FileToDownload = { Constants.K_WEBLIBRARYSQLCE, Constants.K_WEBFRAMEWORKCE, Constants.K_WEBAPPLICATIONMOBILE, Constants.K_WEBAPPLICATIONREADME };
        private string[] m_DestionationFileToDownload = { Constants.K_LOCALLIBRARYSQLCE, Constants.K_LOCALFRAMEWORKCE, Constants.K_LOCALAPPLICATIONMOBILE, Constants.K_LOCALAPPLICATIONREADME };
        private int m_IndexDownload = 0;



        public frmSettingMobile()
        {
            InitializeComponent();
        }
        private void frmSettingMobile_Load(object sender, EventArgs e)
        {
            CheckVersionFiles();

            _MobileDatabase = new FileInfo(Constants.K_EmptySDF);
            m_IndexDownload = 0;

            m_DownloadFile = new DownloadFile(Constants.K_UrlEmptyDatabase, _MobileDatabase.FullName);
            m_DownloadFile.ProgressChanged += new EventHandler<System.Net.DownloadProgressChangedEventArgs>(m_DownloadFile_ProgressChanged);
            m_DownloadFile.FinishDownloadFile += new EventHandler(m_DownloadFile_FinishDownloadFile);

            if (!_MobileDatabase.Exists)
            {
                lblDownloadingDatabase.Visible = true;
                pbDownloadFile.Visible = true;
                m_DownloadFile.StartDownload();
            }
            else
            {
                lblDownloadingDatabase.Visible = false;
                pbDownloadFile.Visible = false;
                m_DownloadFile.OnFinishDownloadFile(this, new EventArgs());

            }
            LoadCombos();
            btnDeploy.Enabled = false;
        }

        private void CheckVersionFiles()
        {
            XMLConfigManager _xmlManager = new XMLConfigManager();

            EBaseSettings _ServerMobileSettings = LSettings.SelectByKey(new EMobileDatabaseSettings());
            EBaseSettings _XmlMobileSettings = _xmlManager.ReadBySetting(new EMobileDatabaseSettings());

            if (_ServerMobileSettings.Value != _XmlMobileSettings.Value)
            {
                if (File.Exists(Constants.K_EmptySDF))
                    File.Delete(Constants.K_EmptySDF);
                if (File.Exists(Constants.K_LOCALAPPLICATIONMOBILE))
                    File.Delete(Constants.K_LOCALAPPLICATIONMOBILE);
                _xmlManager.UpdateValue(_ServerMobileSettings);
            }
        }

        #region Control Events

        private void btnCancel_Click(object sender, EventArgs e)
        {
            m_DownloadFile.CancelDownload();
            this.Close();
        }

        private void btnDeploy_Click(object sender, EventArgs e)
        {

            if (ValidateAll())
            {
                FileInfo _SelectedFile = SelectDatabase();
                if (_SelectedFile != null)
                {
                    SaveSettings();
                    Deploy _deploy = new Deploy(_SelectedFile.FullName, m_MobileSettings);
                    try
                    {
                        _deploy.StartDeploy();
                        MessageBox.Show("Deploy Execute succesfull");
                        this.Close();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Please try with other database");
                        ErrorManager.Log("Exception", "PPIDesktopClient.btnDeploy_Click", ex.Message, ex.StackTrace);
                    }
                }
            }

        }

        private void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlProject.Enabled = (ddlVendor.SelectedIndex > 0);
            ddlUser.Enabled = (ddlVendor.SelectedIndex > 0);

            int _selectedValue = 0;

            //Load de ProjectCombo
            if (ddlVendor.SelectedIndex > -1)
            {
                ListBoxItem _selectedItem = (ListBoxItem)ddlVendor.SelectedItem;

                _selectedValue = ConvertHelper.ToInt32(_selectedItem.Value);

                List<EVendor_Project> _vendorProjects = LVendor_Project.SelectAllIdNameByVendor(_selectedValue);
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlProject, _vendorProjects, typeof(EVendor_Project), "Name", "Vendor_ProjectId", "Select an option...");

                List<EVendor_Contact> _vendorContacts = LVendor_Contacts.SelectAllIdNameByVendor(_selectedValue);
                PPIDesktopClient.General.UIHelper.FillDropDown(ddlUser, _vendorContacts, typeof(EVendor_Contact), "Name", "Vendor_ContactId", "Select an option...");

            }
            ActiveDeployAction();
        }

        private void ddlProject_SelectedIndexChanged(object sender, EventArgs e)
        {
            int _selectedValue = 0;
            projectView1.Visible = false;
            projectView1.SelectedProjectId = Int32.MinValue;
            if (ddlProject.SelectedIndex > -1)
            {
                ListBoxItem _selectedItem = (ListBoxItem)ddlProject.SelectedItem;
                _selectedValue = ConvertHelper.ToInt32(_selectedItem.Value);
                projectView1.Visible = true;
                projectView1.SelectedProjectId = _selectedValue;
                projectView1.LoadData();
            }


            ActiveDeployAction();
        }
        private void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            ActiveDeployAction();
        }
        #endregion

        #region DownloadFile Events

        void m_DownloadFile_ProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            pbDownloadFile.Value = e.ProgressPercentage;
        }

        void m_DownloadFile_FinishDownloadFile(object sender, EventArgs e)
        {
            if (m_IndexDownload <= 3)
            {

                if (!File.Exists(m_DestionationFileToDownload[m_IndexDownload]))
                {

                    m_DownloadFile.SetFileDestination(m_DestionationFileToDownload[m_IndexDownload]);
                    m_DownloadFile.SetUrl(m_FileToDownload[m_IndexDownload]);
                    lblDownloadingDatabase.Visible = true;
                    pbDownloadFile.Visible = true;
                    pbDownloadFile.Value = 0;
                    m_IndexDownload = m_IndexDownload + 1;
                    //m_DownloadFile.ProgressChanged += new EventHandler<System.Net.DownloadProgressChangedEventArgs>(m_DownloadFile_ProgressChanged);
                    //m_DownloadFile.FinishDownloadFile += new EventHandler(m_DownloadFile_FinishDownloadFile);
                    m_DownloadFile.StartDownload();

                }
                else
                {
                    m_IndexDownload = m_IndexDownload + 1;
                    m_DownloadFile.OnFinishDownloadFile(this, new EventArgs());
                }
            }
            else
            {
                pbDownloadFile.Visible = false;
                lblDownloadingDatabase.Visible = false;
            }

        }
        #endregion


        /// <summary>
        /// Opens a brownserdialog and selects a valid mobile database File returning a FileInfo
        /// </summary>
        /// <returns></returns>
        private FileInfo SelectDatabase()
        {
            FolderBrowserDialog _mobileDatabaseBrownser = new FolderBrowserDialog();
            _mobileDatabaseBrownser.ShowNewFolderButton = true;
            DialogResult _dialogResult = _mobileDatabaseBrownser.ShowDialog();
            DirectoryInfo _selectedDestinationDirectory;
            FileInfo _selectedFile = null;
            _MobileDatabase = new FileInfo(Constants.K_EmptySDF);

            if (_dialogResult == DialogResult.OK)
            {
                try
                {
                    _selectedDestinationDirectory = new DirectoryInfo(_mobileDatabaseBrownser.SelectedPath);
                    if (_MobileDatabase.Exists)
                    {
                        _selectedFile = _MobileDatabase.CopyTo(_selectedDestinationDirectory.FullName + Path.DirectorySeparatorChar + Constants.K_NAMEMOBILEDATABASE, true);
                        for (int i = 0; i < m_DestionationFileToDownload.Length; i++)
                        {
                            FileInfo tmpFile = new FileInfo(m_DestionationFileToDownload[i]);
                            tmpFile.CopyTo(_selectedDestinationDirectory.FullName + Path.DirectorySeparatorChar + tmpFile.Name);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Empty Database doestn´t exist in inbox folder");
                        ErrorManager.Log("Information", "frmSettingMobile.SelectDatabase", "the empty database doesn´t exist", "");
                    }
                }
                catch (Exception ex)
                {
                    ErrorManager.Log("Exception", "frmSettingMobile " + ex.Source, ex.Message, ex.StackTrace);
                    _selectedFile = null;
                }
            }
            return _selectedFile;
        }

        /// <summary>
        ///Opens BrowsedFolder which is the destination folder for the new database. 
        ///Copies "empty.sdf"  from the inbox folder to the BrowsedFolder. 
        ///This process ends by configuring the new DB and renames it as "MobileUtiltiy.sdf"
        /// </summary>
        /// <returns></returns>
        private void SaveSettings()
        {

            m_MobileSettings = new ESettingsStructure();

            ListBoxItem _selectedItem = (ListBoxItem)ddlProject.SelectedItem;
            m_MobileSettings.Project.Id = ConvertHelper.ToInt32(_selectedItem.Value);
            m_MobileSettings.Project.Name = _selectedItem.Text;

            _selectedItem = (ListBoxItem)ddlUser.SelectedItem;
            m_MobileSettings.Contact.Id = ConvertHelper.ToInt32(_selectedItem.Value);
            m_MobileSettings.Contact.Name = _selectedItem.Text;

            _selectedItem = (ListBoxItem)ddlUtility.SelectedItem;
            m_MobileSettings.Utility.Id = ConvertHelper.ToInt32(_selectedItem.Value);
            m_MobileSettings.Utility.Name = _selectedItem.Text;

            _selectedItem = (ListBoxItem)ddlVendor.SelectedItem;
            m_MobileSettings.Vendor.Id = ConvertHelper.ToInt32(_selectedItem.Value);
            m_MobileSettings.Vendor.Name = _selectedItem.Text;

            EBaseSettings _ServerMobileSettings = LSettings.SelectByKey(new EMobileDatabaseSettings());
            m_MobileSettings.DatabaseVersion = _ServerMobileSettings.Value;

            _selectedItem = (ListBoxItem)ddlHandheld.SelectedItem;
            if (ConvertHelper.ToInt32(_selectedItem.Value) > 0)
            {
                m_MobileSettings.Handheld.Id = ConvertHelper.ToInt32(_selectedItem.Value);
                m_MobileSettings.Handheld.Name = _selectedItem.Text;
            }
        }

        private void LoadCombos()
        {
            projectView1.ListProjects = LVendor_Project.SelectAll();
            List<PPIDesktopClient.Entities.EUtility> _utilityList = LUtility.SelectAllIdName();
            PPIDesktopClient.General.UIHelper.FillDropDown(ddlUtility, _utilityList, typeof(PPIDesktopClient.Entities.EUtility), "Name", "UtilityId", "Select an option...");

            List<PPIDesktopClient.Entities.EVendor> _vendorList = LVendor.SelectAllIdName();
            PPIDesktopClient.General.UIHelper.FillDropDown(ddlVendor, _vendorList, typeof(PPIDesktopClient.Entities.EVendor), "Name", "VendorId", "Select an option...");

            PPIDesktopClient.General.UIHelper.FillDropDown(ddlHandheld, LHandheld.SelectAllIdName(), typeof(PPIDesktopClient.Entities.EHandheld), "Name", "Id", "Select an option...");
            addingHandheld1.CurrentHandhelds = LHandheld.SelectAllIdName();
        }

        private void ActiveDeployAction()
        {
            if (ddlProject.SelectedIndex > 0 && ddlUser.SelectedIndex > 0 && ddlVendor.SelectedIndex > 0 && ddlUtility.SelectedIndex > 0)
            {
                btnDeploy.Enabled = true;
            }
            else
            {
                btnDeploy.Enabled = false;
            }
        }

        private void btnAddHandheld_Click(object sender, EventArgs e)
        {
            this.addingHandheld1.Show();
        }

        private void addingHandheld1_FinishInsert(object sender, EventArgs e)
        {
            ddlHandheld.Items.Clear();
            PPIDesktopClient.General.UIHelper.FillDropDown(ddlHandheld, addingHandheld1.CurrentHandhelds, typeof(PPIDesktopClient.Entities.EHandheld), "Name", "Id", "Select an option...");
            this.addingHandheld1.Hide();
        }
    }
}
